//
//  GMForgetPasswordViewController.m
//  GuardMan
//
//  Created by steven on 2016/12/15.
//  Copyright © 2016年 steven. All rights reserved.
//

#import "GMForgetPasswordViewController.h"
#import "GMAuthView.h"
#import "GMAuthTextField.h"
#import "GMButton.h"
#import "GMVerificationButton.h"
#import "GMForgotPasswordDataController.h"
#import "GMNewPasswordViewController.h"
#import <MSWeakTimer/MSWeakTimer.h>

@interface GMForgetPasswordViewController ()

@property (nonatomic, strong)NSString *phoneNo;
@property (nonatomic, strong)NSString *verificationCode;
@property (nonatomic, strong)GMAuthView *authView;

@property (nonatomic, strong)MSWeakTimer *timer;
@property (nonatomic, assign)NSInteger remainTime;

@property (nonatomic, strong)GMForgotPasswordDataController *forgotPasswordDataController;

@end

@implementation GMForgetPasswordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.remainTime = 60;
    
    self.forgotPasswordDataController = [[GMForgotPasswordDataController alloc] init];
    
    [self setupContentView];
    
}

#pragma mark - setup content view
- (void)setupContentView {
    self.view.backgroundColor = [UIColor whiteColor];
    // set navigation title
    [self.navigationItem setTitle:@"找回密码"];
    
    // auth base view
    [self.view addSubview:self.authView];
    [self.authView autoPinEdgesToSuperviewEdges];
    
    // verification text field
    [self.authView addSubview:self.verificationTextField];
    [self.verificationTextField autoAlignAxisToSuperviewAxis:ALAxisVertical];
    [self.verificationTextField autoAlignAxis:ALAxisHorizontal toSameAxisOfView:self.authView withOffset:-AUTH_TEXT_FIELD_HEIGHT];
    [self.verificationTextField autoSetDimensionsToSize:CGSizeMake(self.view.frame.size.width*0.8,AUTH_TEXT_FIELD_HEIGHT)];
    
    // phone text field
    [self.authView addSubview:self.phoneTextField];
    [self.phoneTextField autoPinEdge:ALEdgeLeading toEdge:ALEdgeLeading ofView:self.verificationTextField];
    [self.phoneTextField autoPinEdge:ALEdgeBottom toEdge:ALEdgeTop ofView:self.verificationTextField withOffset:-16];
    [self.phoneTextField autoSetDimension:ALDimensionHeight toSize:AUTH_TEXT_FIELD_HEIGHT];
    
    // verification button
    [self.authView addSubview:self.verificationButton];
    [self.verificationButton autoPinEdge:ALEdgeTrailing toEdge:ALEdgeTrailing ofView:self.verificationTextField];
    [self.verificationButton autoAlignAxis:ALAxisHorizontal toSameAxisOfView:self.phoneTextField];
    [self.verificationButton autoPinEdge:ALEdgeLeading toEdge:ALEdgeTrailing ofView:self.phoneTextField withOffset:6];
    [self.verificationButton autoSetDimension:ALDimensionHeight toSize:AUTH_TEXT_FIELD_HEIGHT];
    
    // next step button
    [self.authView addSubview:self.nextButton];
    [self.nextButton autoAlignAxis:ALAxisHorizontal toSameAxisOfView:self.authView withOffset:14];
    [self.nextButton autoAlignAxisToSuperviewAxis:ALAxisVertical];
    [self.nextButton autoSetDimensionsToSize:CGSizeMake(self.view.frame.size.width*0.8,AUTH_TEXT_FIELD_HEIGHT)];
}

#pragma mark - next step
- (void)nextButtonPressed {
    if ([self checkInputForm]) {
        // Check auth code
        NSDictionary *params = @{@"phone_number":self.phoneNo,@"verifyCode":self.verificationCode};
        [self.forgotPasswordDataController checkAuthCodeWithParams:params callback:^(NSString *error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (error == nil) {
                    [self renderSuccessView];
                } else {
                    [self showAlertMessage:error];
                }
            });
        }];
    }
}

#pragma mark - verification button pressed
- (void)verificationButtonPressed {
    [self.phoneTextField resignFirstResponder];
    [self.verificationTextField resignFirstResponder];
    
    NSString *phoneNo = self.phoneTextField.text;
    if (phoneNo.length == 0) {
        [self showAlertMessage:@"请输入手机号"];
    } else if(phoneNo.length != PHONE_LENGTH) {
        [self showAlertMessage:@"请输入正确的手机号"];
    } else {
        
        NSDictionary *params = @{@"mobile":phoneNo};
        // get auth code
        [self.forgotPasswordDataController getAuthCodeWithParams:params callback:^(NSString *error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (error == nil) {
                    NSLog(@"验证码发送成功!");
                    self.timer = [MSWeakTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countDownVerificationTime) userInfo:nil repeats:YES dispatchQueue:dispatch_get_main_queue()];
                } else {
                    [self showAlertMessage:error];
                }
            });
        }];
    }
}

#pragma mark - count down verification time
- (void)countDownVerificationTime {
    // Check if remain time bigger than 60
    if (self.remainTime > 0) {
        self.remainTime -= 1;
        self.verificationButton.enabled = NO;
        self.verificationButton.userInteractionEnabled = NO;
        [self.verificationButton setTitle:[NSString stringWithFormat:@"%02ld秒后重新发送", (long)self.remainTime] forState:UIControlStateNormal];
    } else {
        self.remainTime = 60;
        [self.timer invalidate];
        self.timer = nil;
        self.verificationButton.enabled = YES;
        self.verificationButton.userInteractionEnabled = YES;
        [self.verificationButton setTitle:@"发送验证码" forState:UIControlStateNormal];
    }
    
}

#pragma mark -check input validation
- (BOOL)checkInputForm {
    [self.phoneTextField resignFirstResponder];
    [self.verificationTextField resignFirstResponder];
    
    BOOL checked = NO;
    self.phoneNo = self.phoneTextField.text;
    self.verificationCode = self.verificationTextField.text;
    
    if (self.phoneNo.length == 0) {
        [self showAlertMessage:@"请输入手机号"];
    } else if(self.phoneNo.length != PHONE_LENGTH) {
        [self showAlertMessage:@"请输入正确的手机号"];
    } else if(self.verificationCode.length == 0) {
        [self showAlertMessage:@"请输入验证码"];
    } else {
        checked = YES;
    }
    
    return checked;
}

#pragma mark - render success view
- (void)renderSuccessView {
    NSDictionary *data = self.forgotPasswordDataController.response[@"data"];
    NSString *token = data[@"token"];
    [[NSUserDefaults standardUserDefaults] setObject:token forKey:@"token"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    GMNewPasswordViewController *newPasswordViewController = [[GMNewPasswordViewController alloc] init];
    newPasswordViewController.phoneNo = self.phoneNo;
    newPasswordViewController.verificationCode = self.verificationCode;
    [self.navigationController pushViewController:newPasswordViewController animated:YES];
}

// Getter for authView
- (GMAuthView *)authView {
    if (!_authView) {
        _authView = [[GMAuthView alloc] init];
    }
    
    return _authView;
}

// Getter for nameTextField
- (GMAuthTextField *)phoneTextField {
    if (!_phoneTextField) {
        _phoneTextField = [[GMAuthTextField alloc] init];
        _phoneTextField.placeholder = @"你的手机号";
        _phoneTextField.keyboardType = UIKeyboardTypeNumberPad;
        _phoneTextField.leftView = [self labelWithTitle:@"手机号"];
    }
    
    return _phoneTextField;
}

// Getter for verification text field
- (GMAuthTextField *)verificationTextField {
    if (!_verificationTextField) {
        _verificationTextField = [[GMAuthTextField alloc] init];
        _verificationTextField.keyboardType = UIKeyboardTypeNumberPad;
        _verificationTextField.placeholder = @"你收到的验证码";
        _verificationTextField.leftView = [self labelWithTitle:@"验证码"];
    }
    
    return _verificationTextField;
}

// Getter for verification button
- (GMVerificationButton *)verificationButton {
    if (!_verificationButton) {
        _verificationButton = [[GMVerificationButton alloc] init];
        [_verificationButton setTitle:@"发送验证码" forState:UIControlStateNormal];
        [_verificationButton setContentEdgeInsets:UIEdgeInsetsMake(0, 4, 0, 4)];
        
        if ([UIFont instancesRespondToSelector:@selector(monospacedDigitSystemFontOfSize:weight:)]) {
            _verificationButton.titleLabel.font = [UIFont monospacedDigitSystemFontOfSize:14 weight:UIFontWeightMedium];
        } else {
            _verificationButton.titleLabel.font = [UIFont systemFontOfSize:14 weight:UIFontWeightMedium];
        }
        [_verificationButton addTarget:self action:@selector(verificationButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _verificationButton;
}

// Getter for next step button
- (GMButton *)nextButton {
    if (!_nextButton) {
        _nextButton = [[GMButton alloc] init];
        [_nextButton setTitle:@"下一步" forState:UIControlStateNormal];
        [_nextButton addTarget:self action:@selector(nextButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _nextButton;
}

// Generate left view label
- (UILabel *)labelWithTitle:(NSString *)title {
    UILabel *label = [[UILabel alloc] init];
    label.font = [UIFont systemFontOfSize:AUTH_FONT_SIZE];
    label.text = title;
    [label sizeToFit];
    
    return label;
}

#pragma mark - override back action
-(void) viewWillDisappear:(BOOL)animated
{
    if ([self.navigationController.viewControllers indexOfObject:self]==NSNotFound)
    {
        if (self.timer) {
            [self.timer invalidate];
            self.timer = nil;
        }
    }
    [super viewWillDisappear:animated];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
